﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.ComponentModel;

namespace KDGIPReporter
{
    class IPModel : INotifyPropertyChanged
    {
        private HttpClient _client;
        private string publicIP;
        private string localIP;
        
        public IPModel()
        {
            getLocalIP();
            getPublicIP();

        }

        public string getPublicIP()
        {
            try
            {
                _client = new HttpClient();
                publicIP = _client.GetStringAsync("http://ipecho.net/plain").Result;
                return publicIP;
            }
            catch (Exception ex)
            {
                publicIP = _client.GetStringAsync("http://icanhazip.com/").Result;
                return publicIP;

            }
            
        }

        public string getLocalIP()
        {
             
                NetworkInterface[] netList = NetworkInterface.GetAllNetworkInterfaces();
            foreach(var n in netList)
            {
                IPInterfaceProperties nProps = n.GetIPProperties();
                GatewayIPAddressInformationCollection gateways = nProps.GatewayAddresses;
                if (gateways != null)
                {
                    foreach (var nL in n.GetIPProperties().UnicastAddresses)
                    {
                        if (nL.AddressPreferredLifetime != UInt32.MaxValue)
                        {
                            if (nL.Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                localIP = nL.Address.ToString();
                            }
                        }
                    }

                }
            }
            return localIP;
        }

        #region Properties

        public string PublicIP
        {
            get {return publicIP;}
            set
            {
                publicIP = value;
                OnPropertyChanged("PublicIP");
            }
        }

        public string LocalIP
        {
            get { return localIP; }
            set
            {
                localIP = value;
                OnPropertyChanged("LocalIP");
            }
        }
        #endregion


        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string property)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(property));

            }

        }
    }
}
